package com.apache.websocket;

import com.apache.client.UctCoreClient;
import com.apache.tools.PostHttp;
import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.NameValuePair;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * description:工作流websocket
 * 定义一个org.springframework.web.socket.server.standard.ServerEndpointExporter的bean
 *
 * @author dyh 创建时间：2018年02月13日
 */
@ServerEndpoint("/flowSocket")
@Component
public class FlowWebsocketServer {

    private static CopyOnWriteArraySet<FlowWebsocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    private Session session;

    @OnOpen
    public void onOpen(Session session) throws IOException {
        String sysPass = "sysPass=" + ToolsUtil.getInstance().getValueByKey("websocket_code_pass");
        String str = session.getQueryString();
        if (str.indexOf(sysPass) < 0) {
            session.close();
            return;
        }
        this.session = session;
        webSocketSet.add(this);
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        String sysPass = "sysPass=" + ToolsUtil.getInstance().getValueByKey("websocket_code_pass");
        String str = session.getQueryString();
        if (str.indexOf(sysPass) > -1) {
            // 群发消息
            sendToAll(message);
        }
    }

    public void sendMessage(String message) throws IOException {
        if (session.isOpen()) {
            this.session.getBasicRemote().sendText(message);
        }
    }

    /**
     * Sends <var>text</var> to all currently connected WebSocket clients.
     */
    public void sendToAll(String text) throws IOException {
        String message = sendFlowText(text);
        synchronized (webSocketSet) {
            for (FlowWebsocketServer c : webSocketSet) {
                c.sendMessage(text);
            }
        }
    }

    private String sendFlowText(String processInsId) {
        String flowUrl = UctCoreClient.getConf_Map().get("flow_server")
                + "/flow/core/flow-webservice!getPicNodeInfo.action";
        NameValuePair[] paras = new NameValuePair[1];
        paras[0] = new NameValuePair("processInsId", processInsId);
        String result = PostHttp.postHttpString(flowUrl, paras);
        JSONObject jb = new JSONObject();
        jb.put("processInsId", processInsId);
        if (StrUtil.isNull(result)) {
            jb.put("assignees", "");
            return jb.toString();
        }
        JSONObject json = JSONObject.fromObject(result);
        jb.put("assignees", json.getString("assignees"));
        return jb.toString();
    }
}
